package org.example.jiaxiao.controller;

import org.example.jiaxiao.entity.Coach;
import org.example.jiaxiao.entity.Student;
import org.example.jiaxiao.service.CoachService;
import org.example.jiaxiao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/coach")
public class CoachController {

    @Autowired
    private CoachService coachService;

    @GetMapping("/list")
    public Result getAllCoaches() {
        try {
            List<Coach> coaches = coachService.getAllCoaches();
            return Result.success(coaches);
        } catch (Exception e) {
            return Result.failure("获取教练列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Result getCoachById(@PathVariable("id") Integer coachId) {
        try {
            Coach coach = coachService.getCoachById(coachId);
            if (coach != null) {
                return Result.success(coach);
            } else {
                return Result.failure("未找到指定教练");
            }
        } catch (Exception e) {
            return Result.failure("获取教练信息失败: " + e.getMessage());
        }
    }

    @PostMapping
    public Result addCoach(@RequestBody Coach coach) {
        try {
            int result = coachService.addCoach(coach);
            if (result > 0) {
                return Result.success("添加教练成功");
            } else {
                return Result.failure("添加教练失败");
            }
        } catch (Exception e) {
            return Result.failure("添加教练失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result updateCoach(@PathVariable("id") Integer coachId, @RequestBody Coach coach) {
        try {
            coach.setCoachId(coachId);
            int result = coachService.updateCoach(coach);
            if (result > 0) {
                return Result.success("更新教练成功");
            } else {
                return Result.failure("更新教练失败");
            }
        } catch (Exception e) {
            return Result.failure("更新教练失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result deleteCoach(@PathVariable("id") Integer coachId) {
        try {
            int result = coachService.deleteCoach(coachId);
            if (result > 0) {
                return Result.success("删除教练成功");
            } else {
                return Result.failure("删除教练失败");
            }
        } catch (Exception e) {
            return Result.failure("删除教练失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}/students")
    public Result getStudentsByCoachId(@PathVariable("id") Integer coachId) {
        try {
            List<Student> students = coachService.getStudentsByCoachId(coachId);
            return Result.success(students);
        } catch (Exception e) {
            return Result.failure("获取教练学员列表失败: " + e.getMessage());
        }
    }
}
